package com.qipay.admin.spChannelRule.controller;

import com.qipay.admin.BaseController;
import com.qipay.admin.login.AuthPassport;
import com.qipay.admin.spChannelRule.vo.SpChannelRuleDto;
import com.qipay.admin.tags.PageModel;
import com.qipay.admin.utils.DateUtils;
import com.qipay.admin.utils.SiteHelper;
import com.qipay.baas.model.SpChannelRule;
import com.qipay.scalar.type.ChannelTypeEnum;
import com.qipay.security.UserDetailsServiceImpl;
import com.qipay.sp.SpChannelRuleService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.constraints.NotNull;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Controller
public class SpChannelRuleController extends BaseController {
    private final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    SpChannelRuleService spChannelRuleService;

    //查询入网商户列表
    @AuthPassport(key = "admin")
    @RequestMapping(value = "/sp/channel/rule", method = RequestMethod.GET)
    public ModelAndView list(@RequestParam(value = "spId", required = false, defaultValue = "") Long spId,
                             @RequestParam(value = "p", required = false, defaultValue = "0") int p,
                             @RequestParam(value = "pz", required = false, defaultValue = "10") int pz) throws UnsupportedEncodingException {
        ModelAndView view = createModelAndView("sp-channel-rule-lst");

        long total = spChannelRuleService.countByCondition(spId);
        List<SpChannelRule> lst = null;
        if (total > 0) {
            lst = spChannelRuleService.getByCondition(spId, p, pz);
        }
        view.addObject("total", total);
        view.addObject("lst", lst);

        PageModel pageModel = new PageModel();
        pageModel.setPage(p);
        pageModel.setPageSize(pz);
        pageModel.setUrl(String.format("?spId=%s", spId));
        if(spId==null){
            pageModel.setUrl(String.format("?spId=%s", ""));
        }

        pageModel.setTotal(total);
        view.addObject("page", pageModel);
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/sp/channel/rule/add"}, method = RequestMethod.GET)
    public ModelAndView add() {
        ModelAndView view = createModelAndView("sp-channel-rule-detail");
        view.addObject("isadd", "1");
        view.addObject("channelTypes", mapChannelType());
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = "/sp/channel/rule/save", method = RequestMethod.POST)
    public String save(SpChannelRuleDto dto) {
        if (dto != null) {
            SpChannelRule spChannelRule = null;
            if (dto.getId() != null && dto.getId() > 0) {
              spChannelRule = spChannelRuleService.selectByPrimaryKey(dto.getId());
                SpChannelRule spChannelRule1 = spChannelRuleService.getBySpId(dto.getSpId(),dto.getChannelType());
                if(spChannelRule1!=null&&spChannelRule1.getId()!=dto.getId()){
                    return String.format("redirect:/sp/channel/rule/%s?error=1",dto.getId());
                }

                BeanUtils.copyProperties(dto, spChannelRule);
                spChannelRule.setCurrentTotalAmount((long) (dto.getCurrentTotalAmount() * 100));
                spChannelRule.setMaxTotalAmount((long) (dto.getMaxTotalAmount() * 100));
                spChannelRule.setMaxOrderAmount((long) (dto.getMaxOrderAmount() * 100));
                spChannelRule.setMinOrderAmount((long) (dto.getMinOrderAmount() * 100));
                spChannelRule.setUpdateTime(new Date());
                spChannelRule.setTotalAmountLastTime(DateUtils.parse(dto.getTotalAmountLastTime(), "yyyy-MM-dd"));
                spChannelRule.setMinTimeStop(DateUtils.parse(dto.getMinTimeStop(), "HH:mm"));
                spChannelRule.setMinTimeStopDuration(DateUtils.parse(dto.getMinTimeStopDuration(), "HH:mm"));

                spChannelRuleService.updateByPrimaryKeySelective(spChannelRule);
            } else {
                spChannelRule = new SpChannelRule();
                //判断同一个spid 相同渠道是否重复新增
                SpChannelRule spChannelRule1 = spChannelRuleService.getBySpId(dto.getSpId(),dto.getChannelType());
                if(spChannelRule1!=null){
                    return String.format("redirect:/sp/channel/rule?spId=%s&error=1",dto.getSpId().toString());
                }
                BeanUtils.copyProperties(dto, spChannelRule);
                spChannelRule.setCurrentTotalAmount((long) (dto.getCurrentTotalAmount() * 100));
                spChannelRule.setMaxTotalAmount((long) (dto.getMaxTotalAmount() * 100));
                spChannelRule.setMaxOrderAmount((long) (dto.getMaxOrderAmount() * 100));
                spChannelRule.setMinOrderAmount((long) (dto.getMinOrderAmount() * 100));
                spChannelRule.setMinTimeStop(DateUtils.parse(dto.getTotalAmountLastTime(), "yyyy-MM-dd"));
                spChannelRule.setTotalAmountLastTime(DateUtils.parse(dto.getTotalAmountLastTime(), "yyyy-MM-dd"));
                spChannelRule.setMinTimeStop(DateUtils.parse(dto.getMinTimeStop(), "HH:mm"));
                spChannelRule.setMinTimeStopDuration(DateUtils.parse(dto.getMinTimeStopDuration(), "HH:mm"));
                spChannelRule.setUpdateTime(new Date());
                spChannelRuleService.insert(spChannelRule);
            }
        }
        return "redirect:/sp/channel/rule";
    }
    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/sp/channel/rule/{id:[\\d]+}"}, method = RequestMethod.GET)
    public ModelAndView detail(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                               @PathVariable @NotNull Long id) {
        ModelAndView view = createModelAndView("sp-channel-rule-detail");
        if (id > 0) {
            SpChannelRule spChannelRule= spChannelRuleService.selectByPrimaryKey(id);
            if (spChannelRule != null && spChannelRule.getId() != null) {
                view.addObject("isadd", "0");
                view.addObject("detail", spChannelRule);
                view.addObject("channelTypes", mapChannelType());

                return view;
            }
        }
        return new ModelAndView("redirect:/sp/channel/rule");
    }


    private Map<Byte, String> mapChannelType() {
        Map<Byte, String> map = new TreeMap<>();
        for (ChannelTypeEnum p : ChannelTypeEnum.values()) {
            map.put(p.getType(), p.getInfo());
        }
        return map;
    }
    private Boolean repeatAdd(List<SpChannelRule> spChannelRules ,SpChannelRuleDto dto) {
        Boolean repeatAdd = false;
        for (SpChannelRule spChannelRules1 :spChannelRules){
            if(dto.getId()!=null){
                if( spChannelRules1.getId().equals(dto.getId())&&(spChannelRules1.getChannelType().equals(dto.getChannelType()))) {
                    repeatAdd =  true;
                }
            }else {
                if(spChannelRules1.getChannelType().equals(dto.getChannelType())){
                    repeatAdd= true;
                }
            }
        }
        return repeatAdd;
    }
}
